import React from 'react';
import { connect } from 'react-redux';
import * as routeActions from 'react-router-redux';
import './index.scss';

class Navigation extends React.PureComponent {
  constructor(props) {
    super(props);

    const locationBeforeTransitions = props.locationBeforeTransitions;
    const navPath = locationBeforeTransitions.pathname.split('/');
    navPath.shift();

    this.state = {
      selectedKey: navPath.length > 1 && navPath[1] ? navPath[1] : props.defaultKey,
    };
    this.clickHandle = ::this.clickHandle;
  }
  clickHandle(key) {
    const { dispatch, locationBeforeTransitions } = this.props;
    const navPath = locationBeforeTransitions.pathname.split('/');
    navPath.shift();
    if (key !== this.state.selectedKey) {
      this.setState({ selectedKey: key }, () => {
        dispatch(routeActions.push(`/${navPath[0]}/${key}`));
      });
    }
  }
  render() {
    const { config } = this.props;
    const { selectedKey } = this.state;
    const width = ((1 / config.length) * 100).toFixed(2);
    return (
      <div className="navigation-container" >
        <div className="navigation-wrapper">
          {config.length > 0 && config.map(item =>
            <div
              className={`navigation-item ${selectedKey === item.key ? 'selected-navigation-item' : ''}`}
              key={item.key}
              style={{ width: `${width}%` }}
              onClick={this.clickHandle.bind(this, item.key)}
            >
              {item.name}
            </div>
          )
          }
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return { ...state.routing };
}

export default connect(mapStateToProps)(Navigation);
